package com.agri.service.impl;

import com.agri.dto.ProductQueryDTO;
import com.agri.entity.FinancingProduct;
import com.agri.entity.User;
import com.agri.exception.FinancingException;
import com.agri.mapper.FinancingProductMapper;
import com.agri.mapper.UserMapper;
import com.agri.result.Result;
import com.agri.service.FinancingProductService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.List;

/**
 * 融资产品服务实现类
 * 处理融资产品的CRUD操作和推荐逻辑
 *
 * @author Agri-Fin-Sale Team
 * @since 2025-11-05
 */
@Service
@Transactional
public class FinancingProductServiceImpl implements FinancingProductService {
    @Autowired
    private FinancingProductMapper financingProductMapper;

    @Autowired
    private UserMapper userMapper;

    @Override
    public Result<?> createProduct(FinancingProduct product) {
        // 检查产品编码是否重复
        QueryWrapper<FinancingProduct> wrapper = new QueryWrapper<>();
        wrapper.eq("product_code", product.getProductCode());
        if (financingProductMapper.selectCount(wrapper) > 0) {
            return Result.fail("产品编码已存在");
        }

        int result = financingProductMapper.insert(product);
        if (result > 0) {
            return Result.success("融资产品创建成功");
        }
        return Result.fail("融资产品创建失败");
    }

    @Override
    public Result<?> updateProduct(FinancingProduct product) {
        FinancingProduct existingProduct = financingProductMapper.selectById(product.getId());
        if (existingProduct == null) {
            return Result.fail("融资产品不存在");
        }

        // 检查产品编码是否重复（排除自身）
        QueryWrapper<FinancingProduct> wrapper = new QueryWrapper<>();
        wrapper.eq("product_code", product.getProductCode())
               .ne("id", product.getId());
        if (financingProductMapper.selectCount(wrapper) > 0) {
            return Result.fail("产品编码已存在");
        }

        int result = financingProductMapper.updateById(product);
        if (result > 0) {
            return Result.success("融资产品更新成功");
        }
        return Result.fail("融资产品更新失败");
    }

    @Override
    public Result<?> deleteProduct(Long id) {
        FinancingProduct product = financingProductMapper.selectById(id);
        if (product == null) {
            return Result.fail("融资产品不存在");
        }

        int result = financingProductMapper.deleteById(id);
        if (result > 0) {
            return Result.success("融资产品删除成功");
        }
        return Result.fail("融资产品删除失败");
    }

    @Override
    public Result<?> getProductById(Long id) {
        FinancingProduct product = financingProductMapper.selectById(id);
        if (product == null) {
            return Result.fail("融资产品不存在");
        }
        return Result.success(product);
    }

    @Override
    public Result<?> listProducts(ProductQueryDTO queryDTO) {
        QueryWrapper<FinancingProduct> wrapper = new QueryWrapper<>();

        if (queryDTO.getProductType() != null) {
            wrapper.eq("product_type", queryDTO.getProductType());
        }
        if (queryDTO.getStatus() != null) {
            wrapper.eq("status", queryDTO.getStatus());
        }
        if (queryDTO.getKeyword() != null) {
            wrapper.like("product_name", queryDTO.getKeyword())
                   .or()
                   .like("product_code", queryDTO.getKeyword());
        }
        wrapper.orderByDesc("create_time");

        if (queryDTO.getPage() != null && queryDTO.getSize() != null) {
            Page<FinancingProduct> page = new Page<>(queryDTO.getPage(), queryDTO.getSize());
            IPage<FinancingProduct> result = financingProductMapper.selectPage(page, wrapper);
            return Result.success(result);
        }

        List<FinancingProduct> products = financingProductMapper.selectList(wrapper);
        return Result.success(products);
    }

    @Override
    public Result<?> recommendProducts(Long userId, String cropType, Double loanAmount) {
        User user = userMapper.selectById(userId);
        if (user == null) {
            return Result.fail("用户不存在");
        }

        QueryWrapper<FinancingProduct> wrapper = new QueryWrapper<>();
        wrapper.eq("status", 1); // 只推荐上架的产品

        // 根据作物类型推荐
        if (cropType != null && !cropType.isEmpty()) {
            wrapper.like("applicable_crops", cropType);
        }

        // 根据贷款金额范围推荐
        if (loanAmount != null) {
            wrapper.le("min_amount", loanAmount)
                   .ge("max_amount", loanAmount);
        }

        List<FinancingProduct> recommendedProducts = financingProductMapper.selectList(wrapper);

        // 如果没有匹配的产品，返回所有上架产品
        if (recommendedProducts.isEmpty()) {
            wrapper.clear();
            wrapper.eq("status", 1);
            recommendedProducts = financingProductMapper.selectList(wrapper);
        }

        return Result.success(recommendedProducts);
    }

    @Override
    public Result<?> updateProductStatus(Long id, Integer status) {
        FinancingProduct product = financingProductMapper.selectById(id);
        if (product == null) {
            return Result.fail("融资产品不存在");
        }

        if (!(status == 0 || status == 1)) {
            return Result.fail("状态值不合法");
        }

        product.setStatus(status);
        int result = financingProductMapper.updateById(product);
        if (result > 0) {
            return Result.success("产品状态更新成功");
        }
        return Result.fail("产品状态更新失败");
    }
}